#!/usr/bin/env python3

"""
将路由插入数据库
"""
import os


def get_routes(api_file):
    """
    获取所有的路由
    """
    with open(os.path.abspath(api_file)) as fp:
        routes = fp.readlines()
    return routes


def out_file(sql, save_file):
    """
    保存sql到文件中
    """
    sql = sql.rstrip(',') + ';'
    with open(save_file, 'w') as fp:
        fp.write('use rabc;\n\n')
        fp.write(sql)


def parse_admin_sql(routes):
    """
    解析后台权限
    """
    sql = "insert into bd_authority_admin(method, route) values "
    for route in routes:
        if route is '\n':
            continue
        route = route.split(',')[1].rstrip('\n')

        for method in ['get', 'post', 'put', 'delete']:
            values = '("%s", %s),' % (method, route)
            sql += values

    return sql


def parse_web_sql(routes, save_file):
    """
    解析web路由
    """
    sql = "insert into bd_authority_web(module, flag) values (%s, %s);"
    res = set()
    for route in routes:
        if route is '\n':
            continue
        module = route.split(':')[0]
        flag = route.split(':')[1].rstrip('\n')
        res.add('%s|%s' % (module, flag))

    with open(save_file, 'w') as fp:
        fp.write('use rabc;\n\n')
        for item in res:
            module = item.split('|')[0]
            flag = item.split('|')[1]
            new = sql % (module, flag)
            fp.write(new + '\n')
            fp.flush()


if __name__  == "__main__":
    api_file = "/home/molio/test_ideas/web_auth.txt"
    save_file = '/home/molio/api.sql'
    routes = get_routes(api_file)
    parse_web_sql(routes, save_file)
    #  out_file(sql, save_file)

